import React, { useState, useEffect, useRef } from 'react'
import { useNavigate } from 'react-router-dom'
import { message } from 'antd';
import {HomeOutlined,
  ReadOutlined,
  VideoCameraOutlined,
  RobotOutlined,
  BookOutlined,
  MessageOutlined,
  UserOutlined,
  ProfileOutlined,
  LeftOutlined,
  RightOutlined
} from '@ant-design/icons';
import styles from "./Coursess.module.css";
import axios from 'axios';

export default function Coursess() {
  const [isMenuOpen, setIsMenuOpen] = useState(false);
  const [windowSize, setWindowSize] = useState({
    width: window.innerWidth,
    height: window.innerHeight
  });
  const [activeCategory, setActiveCategory] = useState('all');
  const [courses, setCourses] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  // 添加课程封面轮播状态
  const [courseImageIndexes, setCourseImageIndexes] = useState({});
  const menuRef = useRef(null);
  const navigate = useNavigate();

  // 添加响应式断点
  const isMobile = windowSize.width < 768;
  const isTablet = windowSize.width >= 768 && windowSize.width <= 1024;
  const isDesktop = windowSize.width > 1024;

  // 添加窗口大小变化监听
  useEffect(() => {
    const handleResize = () => {
      setWindowSize({
        width: window.innerWidth,
        height: window.innerHeight
      });
    };

    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  // 处理课程封面切换
  const handleImageChange = (courseId, direction) => {
    console.log(`切换课程 ${courseId} 的图片，方向: ${direction}`);
    setCourseImageIndexes(prev => {
      const currentIndex = prev[courseId] || 0;
      const course = courses.find(c => c.id === courseId);
      const maxIndex = course?.coverImageUrls?.length - 1 || 0;
      
      let newIndex;
      if (direction === 'prev') {
        newIndex = currentIndex > 0 ? currentIndex - 1 : maxIndex;
      } else {
        newIndex = currentIndex < maxIndex ? currentIndex + 1 : 0;
      }
      
      console.log(`课程 ${courseId} 图片索引从 ${currentIndex} 切换到 ${newIndex}，总图片数: ${course?.coverImageUrls?.length || 0}`);
      
      return {
        ...prev,
        [courseId]: newIndex
      };
    });
  };

  // 获取课程数据
  useEffect(() => {
    const fetchCourses = async () => {
      try {
        setLoading(true);
        setError(null);
        
        console.log('开始获取课程数据...');
        const response = await axios.get('http://localhost:3001/api/courses', {
          params: {
            page: 1,
            limit: 50 // 获取更多课程
          },
          timeout: 10000 // 10秒超时
        });

        console.log('API响应:', response.data);

        if (response.data.success) {
          // 转换后端数据格式为前端格式
          const transformedCourses = response.data.data.map(course => {
            // 处理图片路径
            let imageUrl;
            console.log('处理课程图片:', {
              courseName: course.name,
              originalCoverImageUrls: course.coverImageUrls
            });
            
            if (course.coverImageUrls && course.coverImageUrls.length > 0) {
              // 使用第一张图片作为主图
              const firstImage = course.coverImageUrls[0];
              // 如果是相对路径，添加后端服务器地址
              if (firstImage.startsWith('/uploads/')) {
                imageUrl = `http://localhost:3001${firstImage}`;
                console.log('相对路径图片:', imageUrl);
              } else if (firstImage.startsWith('http')) {
                // 如果是完整的URL，直接使用
                imageUrl = firstImage;
                console.log('完整URL图片:', imageUrl);
              } else {
                // 其他情况，添加默认路径
                imageUrl = `http://localhost:3001/uploads/course-images/${firstImage}`;
                console.log('其他路径图片:', imageUrl);
              }
            } else {
              // 使用默认图片
              imageUrl = '/image/1.webp';
              console.log('使用默认图片:', imageUrl);
            }

            return {
              id: course._id,
              title: course.name,
              description: course.description || '暂无描述',
              image: imageUrl,
              coverImageUrls: course.coverImageUrls || [], // 保存所有封面图片
              level: course.level || '初级',
              duration: course.duration || '10课时',
              students: course.students || Math.floor(Math.random() * 100) + 50,
              price: course.price ? `¥${course.price}` : '免费',
              tag: course.tag || '热门',
              category: course.category || 'all'
            };
          });

          console.log('转换后的课程数据:', transformedCourses);
          setCourses(transformedCourses);
        } else {
          console.error('API返回错误:', response.data.message);
          setError(response.data.message || '获取课程数据失败');
        }
      } catch (error) {
        console.error('获取课程数据失败:', error);
        if (error.code === 'ECONNREFUSED') {
          setError('后端服务未运行，显示模拟数据');
          // 使用模拟数据
          setCourses([
            {
              id: '1',
              title: '数学思维训练',
              description: '培养孩子的数学思维能力，提高逻辑推理能力',
              image: '/image/1.webp',
              coverImageUrls: ['/image/1.webp', '/image/2.webp', '/image/3.png'],
              level: '初级',
              duration: '12课时',
              students: 156,
              price: '¥299',
              tag: '热门',
              category: 'math'
            },
            {
              id: '2',
              title: '语文阅读理解',
              description: '提升阅读理解能力，培养文学素养',
              image: '/image/2.webp',
              coverImageUrls: ['/image/2.webp', '/image/3.png', '/image/4.webp'],
              level: '中级',
              duration: '15课时',
              students: 89,
              price: '¥399',
              tag: '推荐',
              category: 'chinese'
            },
            {
              id: '3',
              title: '英语口语训练',
              description: '纯正发音，流利表达，提升英语口语水平',
              image: '/image/3.png',
              coverImageUrls: ['/image/3.png', '/image/4.webp', '/image/5.webp'],
              level: '高级',
              duration: '20课时',
              students: 234,
              price: '¥599',
              tag: '精品',
              category: 'english'
            }
          ]);
        } else {
          setError(error.message || '获取课程数据失败');
        }
      } finally {
        setLoading(false);
      }
    };

    fetchCourses();
  }, []);

  const toggleMenu = () => {
    setIsMenuOpen(!isMenuOpen);
  };

  useEffect(() => {
    const handleClickOutside = (event) => {
      if (menuRef.current && !menuRef.current.contains(event.target)) {
        setIsMenuOpen(false);
      }
    };

    if (isMenuOpen) {
      document.addEventListener('mousedown', handleClickOutside);
    }

    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [isMenuOpen]);

  const drawerOpen = isMenuOpen;

  // 课程分类
  const categories = [
    { id: 'all', name: '全部课程' },
    { id: 'math', name: '数学思维' },
    { id: 'chinese', name: '语文素养' },
    { id: 'english', name: '英语启蒙' },
    { id: 'science', name: '科学探索' },
    { id: 'art', name: '艺术创作' }
  ];

  // 过滤课程
  const filteredCourses = activeCategory === 'all' 
    ? courses 
    : courses.filter(course => course.category === activeCategory);

  const [activeTab, setActiveTab] = useState('/coursess');
  const tabItems = [
    { icon: <HomeOutlined />, label: "首页", path: "/" },
    { icon: <ProfileOutlined />, label: "课程", path: "/coursess" },
    { icon: <ReadOutlined />, label: "图书", path: "/books" },
    { icon: <MessageOutlined />, label: "聊天", path: "/c" },
    { icon: <UserOutlined />, label: "我的", path: "/d" }
  ];

  // 根据当前路径设置active tab
  useEffect(() => {
    const currentPath = window.location.pathname;
    setActiveTab(currentPath);
  }, []);

  // 统一的退出登录处理函数
  const handleLogout = () => {
    // 清除本地存储的用户信息
    localStorage.removeItem('currentUser');
    localStorage.removeItem('token');
    
    message.success('已成功退出登录');
    
    // 延迟跳转到登录页面
    setTimeout(() => {
      navigate('/login');
    }, 1000);
  };

  // 获取当前显示的图片URL
  const getCurrentImageUrl = (course) => {
    const currentIndex = courseImageIndexes[course.id] || 0;
    const imageUrls = course.coverImageUrls || [];
    
    console.log(`课程 ${course.id} 当前图片索引: ${currentIndex}, 总图片数: ${imageUrls.length}`);
    
    if (imageUrls.length === 0) {
      console.log(`课程 ${course.id} 没有封面图片，使用默认图片: ${course.image}`);
      return course.image;
    }
    
    const currentImage = imageUrls[currentIndex];
    let finalUrl;
    
    if (currentImage.startsWith('/uploads/')) {
      finalUrl = `http://localhost:3001${currentImage}`;
      console.log(`课程 ${course.id} 相对路径图片: ${finalUrl}`);
    } else if (currentImage.startsWith('http')) {
      finalUrl = currentImage;
      console.log(`课程 ${course.id} 完整URL图片: ${finalUrl}`);
    } else {
      finalUrl = `http://localhost:3001/uploads/course-images/${currentImage}`;
      console.log(`课程 ${course.id} 其他路径图片: ${finalUrl}`);
    }
    
    return finalUrl;
  };

  // 检查是否有多张图片
  const hasMultipleImages = (course) => {
    return course.coverImageUrls && course.coverImageUrls.length > 1;
  };

  return (
    <div className={styles['course-container']}>
      {/* Header Navigation Bar - 与Home.jsx相同的导航栏 */}
      <header className={styles['header']}>
        <div className={styles['header-content']}>
          {/* Logo */}
          <div className={styles['logo']}>
            <div className={styles['logo-icon']}>
              <div className={`${styles['logo-square']} ${styles['red']}`}></div>
              <div className={`${styles['logo-square']} ${styles['green']}`}></div>
              <div className={`${styles['logo-square']} ${styles['blue']}`}></div>
              <div className={`${styles['logo-square']} ${styles['yellow']}`}></div>
            </div>
            <span className={styles['logo-text']}>智绘师</span>
          </div>

          {/* Navigation Links */}
          <nav className={styles['nav-links']}>
            <a className={styles['nav-link']} onClick={() => navigate('/')}>
              首页
            </a>
            <a className={styles['nav-link']}>
              学习机
            </a>
            <a className={styles['nav-link']}>
              智绘师网校
            </a>
            <a className={`${styles['nav-link']} ${styles['active']}`}>
              培优素养课
            </a>
                         <a className={styles['nav-link']} onClick={() => navigate('/books')}>
               智能图书
             </a>
            <a className={styles['nav-link']}>
              九章大模型
            </a>
            <a className={styles['nav-link']}>
              我们的故事
            </a>
          </nav>

          {/* Right Side Menu */}
          <div className={styles['menu-toggle']} onClick={toggleMenu} ref={menuRef}>
            <div className={styles['hamburger']}>
              <span></span>
              <span></span>
              <span></span>
            </div>
            <span className={styles['menu-text']}>全部</span>
            
            {/* 抽屉菜单 */}
            {drawerOpen && (
              <div className={styles['drawer-overlay']} onClick={toggleMenu}>
                <div 
                  className={`${
                    isMobile ? styles['mobile-drawer'] : 
                    isTablet ? styles['tablet-drawer'] : 
                    styles['desktop-drawer']
                  }`} 
                  onClick={(e) => e.stopPropagation()}
                >
                  <div className={styles['drawer-header']}>
                    <span className={styles['drawer-title']}>智绘师</span>
                    <button className={styles['drawer-close']} onClick={toggleMenu}>×</button>
                  </div>
                  
                  <div className={styles['drawer-content']}>
                    <div className={styles['menu-section']}>
                      <div className={styles['menu-item']}>选课</div>
                      <div className={styles['menu-item']}>学习俱乐部</div>
                      <div className={styles['menu-item']}>课程表</div>
                      <div className={styles['menu-item']}>智绘师移动应用</div>
                      <div className={styles['menu-item']}>智绘卡</div>
                      <div className={styles['menu-item']} onClick={() => navigate('/coursess')}>精品课臻选</div>
                      <div className={styles['menu-item']}>精品课讲堂</div>
                      <div className={styles['menu-item']}>上海智绘课堂</div>
                    </div>
                    
                    <div className={styles['menu-divider']}></div>
                    
                    <div className={styles['menu-section']}>
                      <div className={styles['menu-item']}>关于智绘师</div>
                      <div className={styles['menu-item']}>帮助中心</div>
                    </div>
                    
                    <div className={styles['drawer-footer']}> 
                      <button 
                        className={styles['register-btn']}
                        onClick={handleLogout}
                      >
                        <span className={styles['btn-text']}>退出登录</span>
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            )}
          </div>
        </div>
      </header>

      {/* 页面主要内容 */}
      <main className={styles['main-content']} style={{ 
        paddingBottom: isMobile ? '80px' : '40px' 
      }}>
        <div className={styles['content-wrapper']}>
          {/* 页面标题 */}
          <div className={styles['page-header']}>
            <h1 className={styles['page-title']}>培优素养课</h1>
            <p className={styles['page-subtitle']}>为孩子的全面发展提供优质课程</p>
          </div>

          {/* 课程分类 */}
          <div className={styles['course-categories']}>
            {categories.map(category => (
              <button
                key={category.id}
                className={`${styles['category-btn']} ${
                  activeCategory === category.id ? styles['active'] : ''
                }`}
                onClick={() => setActiveCategory(category.id)}
              >
                {category.name}
              </button>
            ))}
          </div>

          {/* 加载状态 */}
          {loading && (
            <div className={styles['loading-container']}>
              <div className={styles['loading-spinner']}></div>
              <p>正在加载课程...</p>
            </div>
          )}

          {/* 错误状态 */}
          {error && (
            <div className={styles['error-container']}>
              <p>{error}</p>
              {error.includes('后端服务未运行') ? (
                <p style={{ color: '#666', fontSize: '14px', marginTop: '10px' }}>
                  提示：请启动后端服务以显示真实课程数据
                </p>
              ) : (
                <button 
                  className={styles['retry-btn']}
                  onClick={() => window.location.reload()}
                >
                  重新加载
                </button>
              )}
            </div>
          )}

          {/* 课程网格 */}
          {!loading && !error && (
            <div className={styles['course-grid']}>
              {filteredCourses.length > 0 ? (
                filteredCourses.map(course => (
                  <div 
                    key={course.id} 
                    className={styles['course-item']}
                    onClick={() => navigate(`/course-detail/${course.id}`)}
                    style={{ cursor: 'pointer' }}
                  >
                    {course.tag && <span className={styles['course-tag']}>{course.tag}</span>}
                    <div className={styles['course-image-container']}>
                      <div className={styles['course-image']}>
                        <img 
                          src={getCurrentImageUrl(course)} 
                          alt={course.title}
                          onError={(e) => {
                            e.target.src = '/image/1.webp';
                            console.log(`图片加载失败: ${getCurrentImageUrl(course)}`);
                          }}
                        />
                        {/* 图片轮播控制按钮 */}
                        {hasMultipleImages(course) && (
                          <>
                            <button 
                              className={`${styles['image-nav-btn']} ${styles['prev-btn']}`}
                              onClick={(e) => {
                                e.stopPropagation();
                                handleImageChange(course.id, 'prev');
                              }}
                            >
                              <LeftOutlined />
                            </button>
                            <button 
                              className={`${styles['image-nav-btn']} ${styles['next-btn']}`}
                              onClick={(e) => {
                                e.stopPropagation();
                                handleImageChange(course.id, 'next');
                              }}
                            >
                              <RightOutlined />
                            </button>
                            {/* 图片指示器 */}
                            <div className={styles['image-indicators']}>
                              {course.coverImageUrls.map((_, index) => (
                                <span 
                                  key={index}
                                  className={`${styles['indicator']} ${
                                    (courseImageIndexes[course.id] || 0) === index ? styles['active'] : ''
                                  }`}
                                  onClick={(e) => {
                                    e.stopPropagation();
                                    setCourseImageIndexes(prev => ({
                                      ...prev,
                                      [course.id]: index
                                    }));
                                  }}
                                />
                              ))}
                            </div>
                          </>
                        )}
                      </div>
                    </div>
                    <div className={styles['course-info']}>
                      <h3 className={styles['course-title']}>{course.title}</h3>
                      <p className={styles['course-description']}>{course.description}</p>
                      <div className={styles['course-meta']}>
                        <span className={styles['course-level']}>{course.level}</span>
                        <span className={styles['course-duration']}>{course.duration}</span>
                        <span className={styles['course-students']}>{course.students}人学习</span>
                      </div>
                      <div className={styles['course-footer']}>
                        <span className={styles['course-price']}>{course.price}</span>
                        <button 
                          className={styles['enroll-btn']}
                          onClick={(e) => {
                            e.stopPropagation();
                            navigate(`/course-detail/${course.id}`);
                          }}
                        >
                          立即报名
                        </button>
                      </div>
                    </div>
                  </div>
                ))
              ) : (
                <div className={styles['no-courses']}>
                  <p>暂无课程数据</p>
                </div>
              )}
            </div>
          )}
        </div>
      </main>

      {/* 移动端底部导航 */}
      {isMobile && (
        <div className={styles['tab-bar']}>
          {tabItems.map((item) => (
            <div 
              key={item.path} 
              className={`${styles['tab-item']} ${activeTab === item.path ? styles['active'] : ''}`}
              onClick={() => {
                setActiveTab(item.path);
                navigate(item.path);
              }}
            >
              <span className={styles['tab-icon']}>{item.icon}</span>
              <span className={styles['tab-label']}>{item.label}</span>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
